package com.unohacha.qqj.fzdr.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 说明: 系统静态方法支持库
 * 作者: fangkaijin on 2017/5/17.18:02
 * 邮箱: fangkaijin@gmail.com
 */

public class CommonUtils {

    public final static int CLEAN_PUSH_QUEUE = 0x01110888;
    public static final int WEEKDAYS = 7;
    public static String[] WEEK = {"周日","周一","周二","周三","周四","周五","周六"};
    private static final int IO_BUFFER_SIZE = 2* 1024;

    /**
     * 判断网络是否连接
     */
    public static boolean checkNet(Context context)
    {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return info != null;// 网络是否连接
    }

    public static void backgroundAlpha(Activity aty, float alpha)
    {
        WindowManager.LayoutParams lp = aty.getWindow ().getAttributes ();

        if (alpha == 1) {
            aty.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            aty.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }

        lp.alpha = alpha;
        aty.getWindow ().setAttributes ( lp );

//        if (alpha == 1) {
//            aty.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
//        } else {
//            aty.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
//        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (0==dpValue)?0:(int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (0==pxValue)?0:(int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 sp 的单位 转成为 px(像素)
     */
    public static int sp2px(Context context, float sp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (0==sp)?0:(int) (sp * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public static int px2sp(Context context, float px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (0==px)?0:(int) Math.ceil(px / scale);
    }

    public static View getRootView(Activity activity)
    {
        try
        {
            ViewGroup viewGroup = (ViewGroup)activity.findViewById(android.R.id.content);
            if(null!=viewGroup)
            {
                return viewGroup.getChildAt(0);
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            return null;
        }
    }

    @SuppressLint("NewApi")
    public static void loadBackground(View view, Drawable drawable)
    {
        if(getSDKVersion() >= 16)
        {
            view.setBackground(drawable);
        }
        else
        {
            view.setBackgroundDrawable(drawable);
        }
    }

    /**
     * 获取手机系统SDK版本
     *
     * @return 如API 17 则返回 17
     */
    public static int getSDKVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

  

    /**
     * 反射获取资源resId
     * @param paramContext
     * @param paramString
     * @return
     */
    public static int getDrawableId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "mipmap", paramContext.getPackageName());
    }

    public static String formatCon(String str, ShowType showType)
    {
        StringBuilder builder = new StringBuilder();
        switch (showType)
        {
            case SHOW_PHONE:
            {
                //手机显示格式化
                if(!TextUtils.isEmpty(str))
                {
                    builder.append(str.substring(0, 3));
                    builder.append("****");
                    builder.append(str.substring(7, 11));
                }
            }
            break;
            case SHOW_CARD:
            {
                builder.append("**** ");
                builder.append("**** ");
                builder.append("**** ");
                builder.append(str.substring(str.length()-4, str.length()));
            }
            break;
            default:
                break;
        }
        return builder.toString();
    }

    public static byte[] compressBitmapByte(Bitmap bitmap)
    {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, bao);
        byte[] buffer = bao.toByteArray();
        return buffer;
    }

    public static String compressBitmapStr(Bitmap bitmap)
    {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, bao);
        byte[] buffer = bao.toByteArray();
        return Base64.encodeToString(
                buffer, 0, buffer.length,
                Base64.DEFAULT
        );
    }

    public static boolean checkCard(String cardStr)
    {
        Pattern pattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
        //通过Pattern获得Matcher
        Matcher idNumMatcher = pattern.matcher(cardStr);
        //判断用户输入是否为身份证号
        return idNumMatcher.matches();
    }

    /**
     * 验卷，每四位自动跟横线
     * @param editText
     */
    public static void bankCardNumAddSpace(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            String beforeStr = "";
            String afterStr = "";
            String changeStr = "";
            int index = 0;
            boolean changeIndex = true;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeStr = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                afterStr = s.toString();
                if (changeIndex)
                    index = editText.getSelectionStart();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("".equals(s.toString()) || s.toString() == null || beforeStr.equals(afterStr)) {
                    changeIndex = true;
                    return;
                }
                changeIndex = false;
                char c[] = s.toString().replace(" ", "").toCharArray();
                changeStr = "";
                for (int i = 0; i < c.length; i++) {
                    changeStr = changeStr + c[i] + ((i + 1) % 4 == 0 && i + 1 != c.length ? " " : "");
                }
                if (afterStr.length() > beforeStr.length()) {
                    if (changeStr.length() == index + 1) {
                        index = changeStr.length() - afterStr.length() + index;
                    }
                    if (index % 5 == 0 && changeStr.length() > index + 1) {
                        index++;
                    }
                } else if (afterStr.length() < beforeStr.length()) {
                    if ((index + 1) % 5 == 0 && index > 0 && changeStr.length() > index + 1) {
                        //  index--;
                    } else {
                        index = changeStr.length() - afterStr.length() + index;
                        if (afterStr.length() % 5 == 0 && changeStr.length() > index + 1) {
                            index++;
                        }
                    }
                }
                editText.setText(changeStr);
                if(index>=1 && index<=beforeStr.length())
                {
                    editText.setSelection(index);
                }
            }
        });
    }

    //设置手机号显示样式 183******30
    public static String returnPhone(String phone){
        String phone2 = phone.substring(0,3) + "******"  + phone.substring(phone.length() - 4, phone.length());
        return phone2;
    }

    public static void phoneNumAddSpace(final EditText editText)
    {
        editText.addTextChangedListener(new TextWatcher() {
            int beforeTextLength=0;
            int onTextLength=0;
            boolean isChanged = false;

            int location=0;//记录光标的位置
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            int konggeNumberB = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeTextLength = s.length();
                if(buffer.length()>0){
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if(s.charAt(i) == '-'){
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if(onTextLength == beforeTextLength || onTextLength <= 3 || isChanged){
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(isChanged){
                    location = editText.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if(buffer.charAt(index) == '-'){
                            buffer.deleteCharAt(index);
                        }else{
                            index++;
                        }
                    }

                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if((index == 3 || index == 8)){
                            buffer.insert(index, "-");
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if(konggeNumberC>konggeNumberB){
                        location+=(konggeNumberC-konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if(location>str.length()){
                        location = str.length();
                    }else if(location < 0){
                        location = 0;
                    }

                    editText.setText(str);
                    Editable etable = editText.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
    }

    /**
     * 去掉字符中所有空格
     * @param str
     * @return
     */
    public static String cleanSpaceAll(String str)
    {
        return str.replaceAll(" ", "");
    }

    public enum ShowType
    {
        SHOW_PHONE,
        SHOW_CARD
        ;
    }

    /**
     * 获取网络时间毫秒
     */
    public static long getWebsiteMS() {
        URLConnection uc = null;
        try {
            URL url = new URL("http://hotol.cn");// 取得资源对象 http://www.m.baidu.com/
            uc = url.openConnection();// 生成连接对象
            //uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
            if(0==ld)
            {
                return System.currentTimeMillis();
            }
            else
            {
                return ld;
            }
        } catch (Exception e) {
            return System.currentTimeMillis();
        }
    }

    /**
     * 获取当前应用程序的版本号
     */
    public static String obtainVersion(Context context)
    {
        int version = 0;
        try
        {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
            return String.valueOf(version);
        } catch (PackageManager.NameNotFoundException e)
        {
            return String.valueOf("未知");
        }
    }

    /**
     * 获取当前应用程序的版本号
     */
    public static String obtainShowVersion(Context context)
    {
        String version = "0";
        try
        {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e)
        {
            version = "未知";
        }
        return version;
    }

    public static String obtainClientType()
    {
        return "1";
    }


    public static Map<String, String> obtainOrcHeaders(Context context)
    {
        long timestamp = CommonUtils.getWebsiteMS();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept", "*/*");
        headers.put("Host", "api.youtu.qq.com");
        headers.put("user-agent", "youtu-java-sdk");
        headers.put("Content-Type", "text/json");
//        headers.put("Authorization", YouTuUtils.getInstance().obtainSign(System.currentTimeMillis() / 1000 + CommonUtils.EXPIRED_SECONDS, "").toString());
        return headers;
    }

    public static String obtainTimeFormat01(long time)
    {
        DateFormat format;
        Date date = new Date(time);
        Calendar current = Calendar.getInstance();
        current.setTime(date);
        Calendar today = Calendar.getInstance();    //今天
        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH));
        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set( Calendar.HOUR_OF_DAY, 0);
        today.set( Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        if(current.after(today)){
            format = new SimpleDateFormat("hh:mm");
            return "今天 "+format.format(date);
        }else{
            format = new SimpleDateFormat("MM:dd hh:mm");
            return format.format(date);
        }
    }

    public static String obtainDistance(double distance)
    {
        if(distance/1000>=1)
        {
            double i = distance/1000;
            DecimalFormat df = new DecimalFormat("#.00");
            return df.format(i)+"km";
        }
        else
        {
            return distance+"m";
        }
    }

    public static boolean listIsNull(List list)
    {
        if(null==list || list.isEmpty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static String obtainPicktime(long endDoortime)
    {
        if(endDoortime > System.currentTimeMillis())
        {
            long time = endDoortime - System.currentTimeMillis();
            try
            {
                Integer ss = 1000;
                Integer mi = ss * 60;
                Integer hh = mi * 60;

                Long hour = (time) / hh;
                Long minute = (time - hour * hh) / mi;
                Long second = (time - hour * hh - minute * mi) / ss;

                StringBuilder builder = new StringBuilder();
                if(hour > 0) {
                    builder.append(hour+":s");
                }
                else
                {
                    builder.append("00:");
                }
                if(minute > 0) {
                    builder.append(minute+":");
                }
                else
                {
                    builder.append("00:");
                }
                if(second > 0)
                {
                    builder.append(second+"");
                }
                else
                {
                    builder.append("00");
                }

                return builder.toString();
            }
            catch (NumberFormatException e)
            {
                return "00:00:00";
            }
        }
        else
        {
            return "已超时";
        }
    }

    public static String obtainTimeFormat02(long time)
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }

    }

    public static String obtainTimeFormat08(long time)
    {
        DateFormat format = new SimpleDateFormat("yyyy年MM月");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }

    }

    public static String obtainTimeFormat04(long time)
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }

    }

    public static String obtainMoney(double money, int i)
    {
        BigDecimal bg = new BigDecimal(money);
        double f1 = bg.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1+"元";
    }

    public static String obtainTimeFormat03(long time)
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }
    }

    public static String obtainTimeFormat05(long time)
    {
        DateFormat format = new SimpleDateFormat("HH:mm:ss");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }
    }

    public static String obtainTimeFormat07(long time)
    {
        DateFormat format = new SimpleDateFormat("HH:mm");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }
    }

    public static String obtainTimeFormat06(long time)
    {
        DateFormat format = new SimpleDateFormat("MM-dd");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }
    }

    public static String obtainDateMD(Date date){
        DateFormat format = new SimpleDateFormat("MM-dd");

        return format.format(date);
    }

    public static String ontainDateHM(Date date){
        DateFormat format = new SimpleDateFormat("HH:mm");

        return format.format(date);
    }

    public static String obtainTimeFormatMD(long time)
    {
        DateFormat format = new SimpleDateFormat("MM-dd");
        try
        {
            Date date = new Date(time);
            return format.format(date);
        }
        catch (Exception e)
        {
            return format.format(new Date());
        }

    }

    public static String obtainTimeFormatHM(long time)
    {
        DateFormat format = new SimpleDateFormat("HH:mm");
        try
        {
            Date date = new Date(time);
            return getWeek(time) + "" + format.format(date);
        }
        catch (Exception e)
        {
            return getWeek(time) + "" + format.format(new Date());
        }

    }

    public static String DateToWeekAndTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }

        return WEEK[dayIndex - 1] +  ontainDateHM(date);
    }

    private static String getWeek(long timeStamp) {
        int mydate = 0;
        String week = null;
        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date(timeStamp));
        mydate = cd.get(Calendar.DAY_OF_WEEK);
        // 获取指定日期转换成星期几
        if (mydate == 1) {
            week = "周日";
        } else if (mydate == 2) {
            week = "周一";
        } else if (mydate == 3) {
            week = "周二";
        } else if (mydate == 4) {
            week = "周三";
        } else if (mydate == 5) {
            week = "周四";
        } else if (mydate == 6) {
            week = "周五";
        } else if (mydate == 7) {
            week = "周六";
        }
        return week;
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                return null;
            }
        }
        return result;
    }

    /**
     * function : 通过给定的图片路径生成对应的bitmap
     * author   : ZhaoYanDong
     * time     : 2017/3/28 0028
     * version  : 3.3.0
     * params   :
     * return   :
     */
    public static Bitmap obtainBitmap(String imgPath, int scale) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        int widthSample = (int) (imageWidth / scale);
        int heightSample = (int) (imageHeight / scale);
        // 计算缩放比例
        options.inSampleSize = widthSample < heightSample ? heightSample
                : widthSample;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(imgPath, options);
    }

    /**
     *
     * 根据bitmap压缩图片质量
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    public static Bitmap cQuality(Bitmap bitmap){
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        int beginRate = 100;
        //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
        while(bOut.size()/(1024*1024)>3){  //如果压缩后大于3m，则提高压缩率，重新压缩
            beginRate -=10;
            bOut.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
        }
        ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        if(newBitmap!=null){
            return newBitmap;
        }else{
            return bitmap;
        }
    }

    /**
     * base64转为bitmap
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static File saveBitmapFile(Bitmap bitmap){
        String fileName = "cache.jpg";
        BufferedOutputStream bos = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory()+"/suyhAgent/imgCache";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file=new File(path +"/"+fileName);//将要保存图片的路径
            try {
                bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                return file;
            } catch (IOException e) {
                return null;
            }
            finally
            {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    return null;
                }
            }
        }
        else
        {
            return null;
        }
    }

//    public static int obtainAreaId(List<GeoBean> geoList, String provinceName, String cityName, String areanName)
//    {
//        if(null==geoList||geoList.isEmpty())
//        {
//            return 0;
//        }
//        else if(TextUtils.isEmpty(provinceName))
//        {
//            return 0;
//        }
//        else if(TextUtils.isEmpty(cityName))
//        {
//            return 0;
//        }
//        else if(TextUtils.isEmpty(areanName))
//        {
//            return 0;
//        }
//        else
//        {
//            GeoBean geoInner = null;
//            for(GeoBean geo:geoList)
//            {
//                if(provinceName.equals(geo.province_name))
//                {
//                    geoInner = geo;
//                    break;
//                }
//            }
//            if(null==geoInner)
//            {
//                return 0;
//            }
//            else
//            {
//                GeoBean.CityBean cityInner = null;
//                for(GeoBean.CityBean city:geoInner.city_list)
//                {
//                    if(cityName.equals(city.city_name))
//                    {
//                        cityInner = city;
//                        break;
//                    }
//                }
//                if(null==cityInner)
//                {
//                    return 0;
//                }
//                else
//                {
//                    GeoBean.CityBean.AreaBean areaInner = null;
//                    for(GeoBean.CityBean.AreaBean area:cityInner.area_list)
//                    {
//                        if(areanName.equals(area.area_name))
//                        {
//                            areaInner = area;
//                            break;
//                        }
//                    }
//                    if(null==areaInner)
//                    {
//                        return 0;
//                    }
//                    else
//                    {
//                        return areaInner.dict_id;
//                    }
//                }
//            }
//        }
//    }

//    public static int[] obtainGeoCode(List<GeoBean> geoList, String provinceName, String cityName, String areanName)
//    {
//        int[] result = new int[3];
//        if(null==geoList||geoList.isEmpty())
//        {
//            return new int[0];
//        }
//        else if(TextUtils.isEmpty(provinceName))
//        {
//            return new int[0];
//        }
//        else if(TextUtils.isEmpty(cityName))
//        {
//            return new int[0];
//        }
//        else if(TextUtils.isEmpty(areanName))
//        {
//            return new int[0];
//        }
//        else
//        {
//            GeoBean geoInner = null;
//            for(GeoBean geo:geoList)
//            {
//                if(provinceName.equals(geo.province_name))
//                {
//                    geoInner = geo;
//                    break;
//                }
//            }
//            if(null==geoInner)
//            {
//                return new int[0];
//            }
//            else
//            {
//                result[0] = geoInner.dict_id;
//                GeoBean.CityBean cityInner = null;
//                for(GeoBean.CityBean city:geoInner.city_list)
//                {
//                    if(cityName.equals(city.city_name))
//                    {
//                        cityInner = city;
//                        break;
//                    }
//                }
//                if(null==cityInner)
//                {
//                    return new int[0];
//                }
//                else
//                {
//                    result[1] = cityInner.dict_id;
//                    GeoBean.CityBean.AreaBean areaInner = null;
//                    for(GeoBean.CityBean.AreaBean area:cityInner.area_list)
//                    {
//                        if(areanName.equals(area.area_name))
//                        {
//                            areaInner = area;
//                            break;
//                        }
//                    }
//                    if(null==areaInner)
//                    {
//                        return new int[0];
//                    }
//                    else
//                    {
//                        result[2] = areaInner.dict_id;
//                    }
//                }
//            }
//        }
//        return result;
//    }

    public static long obtainTimeLong(String timeStr)
    {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        Date date = null;
        try {
            date = format1.parse(timeStr);
            String cur = format2.format(date);
            return Timestamp.valueOf(cur).getTime();
        }
        catch (IllegalArgumentException e)
        {
            return System.currentTimeMillis();
        }
        catch (ParseException e) {
            date = new Date();
            String cur = format2.format(date);
            return Timestamp.valueOf(cur).getTime();
        }
    }

    public static int obtainSexTag(String sexTag)
    {
        if("男".equals(sexTag))
        {
            return 1;
        }
        else if("女".equals(sexTag))
        {
            return 2;
        }
        else
        {
            return 3;
        }
    }

//    public static void collapseStatusBar(Context context)
//    {
//        try
//        {
//            Object statusBarManager = context.getSystemService("statusbar");
//            Method collapse;
//            if (getSDKVersion() <= 16)
//            {
//                collapse = statusBarManager.getClass().getMethod("collapse");
//            }
//            else
//            {
//                collapse = statusBarManager.getClass().getMethod("collapsePanels");
//            }
//            collapse.invoke(statusBarManager);
//        }
//        catch (Exception localException)
//        {
//
//        }
//    }
    /**
     * 反射获取资源resId
     * @param context
     * @param resType
     * @param resStr
     * @return
     */
    public static int obtainDrawableId(Context context, String resType, String resStr) {
        return context.getResources().getIdentifier(resStr,
                resType, context.getPackageName());
    }

    /**
     * 读取assets文件
     */
    public static String obtainFileFromAssets(String fileName,  Resources resources)
    {
        InputStream is = null;
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            is = resources.getAssets().open(fileName);
            reader = new InputStreamReader(is);
            bufferedReader = new BufferedReader(reader);
            StringBuilder builder = new StringBuilder();
            String str = null;
            while((str = bufferedReader.readLine())!=null){
                builder.append(str);
            }
            return builder.toString();
        } catch (Exception e) {
            return null;
        }
        finally {
            if(null!=bufferedReader)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=reader)
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=is)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    /**
//     * 获取渠道名
//     * @param context 此处习惯性的设置为activity，实际上context就可以
//     * @return 如果没有获取成功，那么返回值为空
//     */
//    public static String getChannelName(Context context) {
//        if (context == null) {
//            return null;
//        }
//        String channelName = null;
//        try {
//            PackageManager packageManager = context.getPackageManager();
//            if (packageManager != null) {
//                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
//                ApplicationInfo applicationInfo = packageManager.
//                        getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
//                if (applicationInfo != null) {
//                    if (applicationInfo.metaData != null) {
//                        channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
//                    }
//                }
//
//            }
//        } catch (PackageManager.NameNotFoundException e) {
//            channelName = "deflaut_channel";
//        }
//        return channelName;
//    }

//    public static int obtainChannelId(Context context)
//    {
//        String channelName = getChannelName(context);
//        int channeld;
//        switch (channelName)
//        {
//            case "wandoujia":
//                channeld = 1;
//                break;
//
//            case "baidu":
//                channeld = 2;
//                break;
//
//            case "c360":
//                channeld = 3;
//                break;
//
//            case "yingyongbao":
//                channeld = 4;
//                break;
//
//            case "huawei":
//                channeld = 5;
//                break;
//
//            case "xiaomi":
//                channeld = 6;
//                break;
//
//            case "tuiguang":
//                channeld = 7;
//                break;
//            default:
//            {
//                channeld = 0;
//            }
//            break;
//        }
//        return channeld;
//    }



    public static long dateToLong(Date date)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String cur = format.format(date);
            return Timestamp.valueOf(cur).getTime();
        }
        catch (IllegalArgumentException e)
        {
            return System.currentTimeMillis();
        }
    }

//    public static String removeSpace(String str)
//    {
//        return str.replaceAll("\\s*", "");
//    }

//    public static boolean inTowHourNow(SendInitResponeBean.SendInitInnerBean.WorkTimeBean workTime)
//    {
//        try
//        {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String starTime = workTime.start_time;
//            String endTime = workTime.end_time;
//            Calendar calendar = Calendar.getInstance();
//            int year = calendar.get(Calendar.YEAR);
//            int mon = calendar.get(Calendar.MONTH)+1;
//            int day = calendar.get(Calendar.DATE);
//            String startTimeStr = year+"-"+mon+"-"+day+" "+starTime+":00";
//            String endTimeStr = year+"-"+mon+"-"+day+" "+endTime+":00";
//            long startLong = dateToLong(format.parse(startTimeStr));
//            long endLong = dateToLong(format.parse(endTimeStr));
//            long nowLong = System.currentTimeMillis();
//            if(startLong<=nowLong&&endLong>=nowLong)
//            {
//                return true;
//            }
//            else
//            {
//                return false;
//            }
//        } catch (ParseException e) {
//            return false;
//        }
//    }

//    public static boolean isWorkEnd(SendInitResponeBean.SendInitInnerBean.WorkTimeBean workTime)
//    {
//        try
//        {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String endTime = workTime.end_time;
//            Calendar calendar = Calendar.getInstance();
//            int year = calendar.get(Calendar.YEAR);
//            int mon = calendar.get(Calendar.MONTH)+1;
//            int day = calendar.get(Calendar.DATE);
//            String endTimeStr = year+"-"+mon+"-"+day+" "+endTime+":00";
//            long endLong = dateToLong(format.parse(endTimeStr));
//            long nowLong = System.currentTimeMillis();
//            if(endLong>=nowLong)
//            {
//                return true;
//            }
//            else
//            {
//                return false;
//            }
//        } catch (ParseException e) {
//            return false;
//        }
//    }

//    public static boolean inHalfHourNow(SendInitResponeBean.SendInitInnerBean.WorkTimeBean workTime)
//    {
//        try
//        {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String starTime = workTime.half_start_time;
//            String endTime = workTime.half_end_time;
//            Calendar calendar = Calendar.getInstance();
//            int year = calendar.get(Calendar.YEAR);
//            int mon = calendar.get(Calendar.MONTH)+1;
//            int day = calendar.get(Calendar.DATE);
//            String startTimeStr = year+"-"+mon+"-"+day+" "+starTime+":00";
//            String endTimeStr = year+"-"+mon+"-"+day+" "+endTime+":00";
//            long startLong = dateToLong(format.parse(startTimeStr));
//            long endLong = dateToLong(format.parse(endTimeStr));
//            long nowLong = System.currentTimeMillis();
//            if(startLong<=nowLong&&endLong>=nowLong)
//            {
//                return true;
//            }
//            else
//            {
//                return false;
//            }
//        } catch (ParseException e) {
//            return false;
//        }
//    }

    public static long obtainTimeLong01(long start)
    {
        long difference = 2*60*60*1000;
        return start+difference;
    }

    public static long obtainTimeLong02(long start)
    {

        long difference = 30*60*1000;
        return start+difference;
    }

    public static long obtainTimeLong03(String timeBean, int type)
    {
        try
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format01 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String day = format.format(new Date());
            String[] time = timeBean.split("-");
            return dateToLong(format01.parse(day+" "+time[type]+":00"));
        }
        catch (ParseException e) {
            return 0;
        }
    }

    public static long obtainTimeLong04(String timeBean, int type)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        try
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format01 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String day = format.format(calendar.getTime());
            String[] time = timeBean.split("-");
            return dateToLong(format01.parse(day+" "+time[type]+":00"));
        }
        catch (ParseException e) {
            return 0;
        }
    }

    public static double obtainMoney(double money)
    {
        return new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static double obtainMoney01(double money)
    {
        return new BigDecimal(money).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    //保留两位小数
    public static String obtainMoneyFormat01(double money)
    {
        NumberFormat format = NumberFormat.getInstance();
        format.setGroupingUsed(false);
        double d = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return format.format(d);
    }

    //保留两位小数
    public static String obtainMonyFormat1(double money){

        DecimalFormat decimalFormat =new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String money2 = decimalFormat.format(money);//format 返回的是字符串
        return money2;
    }

//    public static String addParams(Context context, String url, double latitude, double longitude)
//    {
//        long timestamp = CommonUtils.getWebsiteMS();
//        String SignInfo = AESUtils.getMD5Code(timestamp+"hotol");
//        StringBuilder builder = new StringBuilder();
//        builder.append(url);
//        if(url.contains("?"))
//        {
//            builder.append("&memb_register_latitude=");
//            builder.append(latitude);
//            builder.append("&memb_register_longitude=");
//            builder.append(longitude);
//            builder.append("&version=");
//            builder.append(BuildConfig.HTTP_VERSION);
//            builder.append("&Timestamp=");
//            builder.append(timestamp);
//            builder.append("&SignInfo=");
//            builder.append(SignInfo);
//            builder.append("&client_type=");
//            builder.append(CommonUtils.obtainClientType());
//            builder.append("&token=");
//            builder.append((null==CConfigure.obtainToken(context))?"":CConfigure.obtainToken(context));
//            builder.append("&device_number=");
//            builder.append(obtainDeviceUUID(context));
//            builder.append("&app_version=");
//            builder.append(obtainVersion(context));
//
//        }
//        else
//        {
//            builder.append("?memb_register_latitude=");
//            builder.append(latitude);
//            builder.append("&memb_register_longitude=");
//            builder.append(longitude);
//            builder.append("&version=");
//            builder.append(BuildConfig.HTTP_VERSION);
//            builder.append("&Timestamp=");
//            builder.append(timestamp);
//            builder.append("&SignInfo=");
//            builder.append(SignInfo);
//            builder.append("&client_type=");
//            builder.append(CommonUtils.obtainClientType());
//            builder.append("&token=");
//            builder.append((null==CConfigure.obtainToken(context))?"":CConfigure.obtainToken(context));
//            builder.append("&device_number=");
//            builder.append(obtainDeviceUUID(context));
//            builder.append("&app_version=");
//            builder.append(obtainVersion(context));
//        }
//        return builder.toString();
//    }

    public static void copy(Context context, String str)
    {
        if(11>=getSDKVersion())
        {
            android.text.ClipboardManager clipboardManager =
                    (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setText(str.trim());
        }
        else
        {
            ClipboardManager clipboardManager =
                    (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData myClip = ClipData.newPlainText("text", str.trim());
            clipboardManager.setPrimaryClip(myClip);
        }
    }

    /**
     * function:  判断app是否在后台
     */
    public static boolean isAppBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }

    public static ActivityManager.RunningTaskInfo getTopTask(Context context, ActivityManager activityManager)
    {
        if(null==activityManager)
        {
            activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        }
        List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            return tasks.get(0);
        }

        return null;
    }

    public static boolean isTopActivity(
            ActivityManager.RunningTaskInfo topTask,
            String packageName,
            String activityName) {
        if (topTask != null) {
            ComponentName topActivity = topTask.topActivity;

            if (topActivity.getPackageName().equals(packageName) &&
                    topActivity.getClassName().equals(activityName)) {
                return true;
            }
        }

        return false;
    }

//    public static boolean isSendTime(int choiceTimeType, SendInitResponeBean.SendInitInnerBean.WorkTimeBean workTime)
//    {
//        if(null==workTime)
//        {
//            return false;
//        }
//        else
//        {
//            if(0==choiceTimeType)
//            {
//                return false;
//            }
//            else if(1==choiceTimeType)
//            {
//                //2小时内
//                if(CommonUtils.inTowHourNow(workTime))
//                {
//                    return true;
//                }
//                else
//                {
//                    return false;
//                }
//            }
//            else if(2==choiceTimeType)
//            {
//                //半小时内
//                if(CommonUtils.inHalfHourNow(workTime))
//                {
//                    return true;
//                }
//                else
//                {
//                    return false;
//                }
//            }
//            else if(3==choiceTimeType)
//            {
//                //今天
//                if(CommonUtils.isWorkEnd(workTime))
//                {
//                    return true;
//                }
//                else
//                {
//                    return false;
//                }
//            }
//            else if(4==choiceTimeType)
//            {
//                return true;
//            }
//            else
//            {
//                return false;
//            }
//        }
//    }

    /**
     * 获取两个日期之间的间隔天数
     * @return
     */
    public static int getGapCount(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
    }

    public static int getGapCountTime(Date startDate, Date endDate){

        long startTime = dateToLong(startDate);
        long endTime = dateToLong(endDate);
        long lastTime = endTime - startTime;
        int betweenDate = 0;

        if (lastTime % (60 * 60 * 24 * 1000) >0){
            betweenDate = (int) (lastTime /(60 * 60 * 24 * 1000)) + 1;
        }else {
            betweenDate = (int) (lastTime /(60 * 60 * 24 * 1000));
        }
        return betweenDate;
    }

    /**
     * 判断两个时间间隔
     * @param startDate
     * @param endDate
     * @return
     */
     public static int getDateBetwween(Date startDate,Date endDate){
         Calendar fromCalendar = Calendar.getInstance();
         fromCalendar.setTime(startDate);
         fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
         fromCalendar.set(Calendar.MINUTE, 0);
         fromCalendar.set(Calendar.SECOND, 0);
         fromCalendar.set(Calendar.MILLISECOND, 0);

         Calendar toCalendar = Calendar.getInstance();
         toCalendar.setTime(endDate);
         toCalendar.set(Calendar.HOUR_OF_DAY, 0);
         toCalendar.set(Calendar.MINUTE, 0);
         toCalendar.set(Calendar.SECOND, 0);
         toCalendar.set(Calendar.MILLISECOND, 0);
         return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
     }

    // currentTime要转换的long类型的时间
    // formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    public static Date longToDate(long currentTime, String formatType)
            throws ParseException {
        Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
        Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
        return date;
    }

    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType)
            throws ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }


    /**
     * 将网络图片的路径转为bitmap
     * @param url
     * @return
     */
    public static Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {

            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() 
                != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

  public static  Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
}